package com.matrix.basecore.utils

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView


class RecyclerViewOnScrollListener : RecyclerView.OnScrollListener() {
    //监听回调
    private var listener: UpPullOnScrollListener? = null

    fun RecyclerViewOnScrollListener(listener: UpPullOnScrollListener?) {
        this.listener = listener
    }

    var isUpScroll: Boolean = false //是否正在上滑标记

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        val manager = recyclerView.layoutManager as LinearLayoutManager?

        if (newState == RecyclerView.SCROLL_STATE_IDLE) { //当前未滑动
            val itemCount = manager!!.itemCount //总数
            val lastItemPosition = manager!!.findLastCompletelyVisibleItemPosition() //最后显示的位置

            if (lastItemPosition == (itemCount - 1) && isUpScroll) {
                listener!!.onLoadMore()
            }
            val fristItemPosition = manager!!.findFirstCompletelyVisibleItemPosition() //第一个显示的位置
            if (fristItemPosition == (0) && !isUpScroll) {
                listener!!.onRefresh()
            }
        }
    }

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
        isUpScroll = dy > 0
    }

    interface UpPullOnScrollListener {
        fun onLoadMore() //上拉加载更多的方法
        fun onRefresh() //下拉刷新的方法
    }
}